<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8" />
  <title>导出学生报名信息</title>
  <link rel="icon" type="image/x-icon" href="images/favicon.png" />
  <style type="text/css">
    body {
      margin: 0 8px;
      font-family: cursive;
      font-size: 14px;
    }
    #tableBody {
      width: 100%;
      border-collapse: collapse;
      border: 1px solid black;
    }
    #tableBody td, #tableBody th {
      border: 1px solid black;
      padding: 0 8px;
    }
    #tableBody caption {
      margin: 32px 0;
    }
    #tableHead, #tableFoot {
      text-align: left;
      height: 32px;
      line-height: 32px;
    }
    .row {
      height: 32px;
    }
    font {
      font-family: cursive;
    }
  </style>
  <script type="text/javascript">
    var title = '学生信息';
    var residTypeMapping = {
      140402: '潞州区',
      140403: '潞州区',
      140411: '潞州区',

      140404: '上党区',
      140421: '上党区',

      140405: '屯留区',
      140424: '屯留区',

      140406: '潞城区',
      140481: '潞城区',

      140423: '襄垣县',
      140425: '平顺县',
      140426: '黎城县',
      140427: '壶关县',
      140428: '长子县',
      140429: '武乡县',
      140430: '沁县',
      140431: '沁源县',

      0: '外地',
    };

    window.onload = init;

    function init() {
      var errMsg = '';
      var dom = document.getElementById('page');
      var data = localStorage.getItem('studentData');
      if (!data) errMsg = '数据不能为空';
      var counts = localStorage.getItem('studentCounts');
      if (!errMsg && !counts) errMsg = '统计不能为空';
      if (errMsg) {
        dom.textContent = errMsg;
        return;
      }

      try {
        data = JSON.parse(data);
        counts = JSON.parse(counts);
      } catch (e) {
        errMsg = e.toString();
      }
      if (errMsg) {
        dom.textContent = errMsg;
        return;
      }

      var html = '';
      var newData = funcRender(data);

      for (var i = 0; i < newData.length; i += 1) {
        var r = newData[i];
        console.log(r);
        html += '<tr>';
        var values = [
          i + 1, r.name, r.sex, r.specialName, r.lodging, r.residType, r.phone,
          r.idCardNum, r.examCardNum, r.signup, r.sum, r.address,
          r.school, r.feeTime, r.fee, '　　　　　　　　',
        ];
        for (var j = 0; j < values.length; j += 1) {
          var value = values[j];
          var addClass = j ? '' : ' class="row"';
          html += '<td align="center"' + addClass + '>' + wrapText(value) + '</td>';
        }
        html += '</tr>';
      }

      if (html) {
        dom = document.getElementById('tableBody');
        dom.getElementsByTagName('tbody')[0].innerHTML = html;

        var c = counts;
        var footerData = [];
        if (c.total) footerData.push('学生总数：' + c.total + '人');
        if (c.lodging1sex1) footerData.push('住校男生：' + c.lodging1sex1 + '人');
        if (c.lodging1sex0) footerData.push('住校女生：' + c.lodging1sex0 + '人');
        if (c.lodging0sex1) footerData.push('跑堂男生：' + c.lodging0sex1 + '人');
        if (c.lodging0sex0) footerData.push('跑堂女生：' + c.lodging0sex0 + '人');
        if (c.exitsex1) footerData.push('退学男生：' + c.exitsex1 + '人');
        if (c.exitsex0) footerData.push('退学女生：' + c.exitsex0 + '人');

        var footer = footerData.toString().replace(/,/g, '，');
        dom = document.getElementById('tableFoot');
        dom.children[0].textContent = footer;

        var title = localStorage.getItem('studentTitle');
        if (title) {
          dom = document.getElementById('tableHead');
          dom.children[0].textContent = title;
        }
      }

      funcSave();
    }

    // 渲染数据, 使之显示更加合理
    function funcRender(data) {
      return data.map(function(item) {
        var newItem = item;
        newItem.sex = item.sex === '1' ? '男' : '女';
        newItem.lodging = item.lodging === '1' ? '住校' : '不住校';
        newItem.sum += '分';
        newItem.fee = item.fee > 0 ? item.fee + '元' : '';
        newItem.feeTime = item.feeTime.substr(0, 10);
        newItem.residType = residTypeMapping[item.idCardNum.substr(0, 6)] || '外地';

        // 防止显示为科学计数格式
        if (item.idCardNum.length === 18 && !isNaN(item.idCardNum)) {
          newItem.idCardNum += '_';
        }
        if (item.examCardNum.length >= 12) {
          newItem.examCardNum += '_';
        }
        if (item.signup.length >= 12) {
          newItem.signup += '_';
        }
        return newItem;
      });
    }

    // 包裹文字
    function wrapText(text) {
      return '<font face="楷体">' + text + '</font>';
    }

    // 保存文件
    function funcSave() {
      // 参考自：HTML中的table导出为Excel文件
      // https://www.cnblogs.com/hill-foryou/p/9224778.html
      var uri = 'data:application/vnd.ms-excel;base64,';
      var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
      var base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) };
      var format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) };
      var dom = document.getElementById('page');
      var content = { worksheet: title, table: dom.innerHTML };
      console.log(content);

      var a = document.createElement('a');
      a.href = uri + base64(format(template, content));
      a.download = title + new Date().toISOString().split('T')[0] + '.xls';
      a.click();
    }
  </script>
</head>
<body>
<div id="page">
  <table id="tableBody">
    <caption>
      <font face="楷体" size="6" style="font-weight:bold;">
        学生信息
      </font>
    </caption>
    <thead>
    <tr>
      <td id="tableHead" colspan="15">
        <font face="楷体"></font>
      </td>
    </tr>
    <tr>
      <th style="min-width:30px;" class="row"><font face="楷体">序号</font></th>
      <th style="min-width:60px;"><font face="楷体">学生姓名</font></th>
      <th style="min-width:30px;"><font face="楷体">性别</font></th>
      <th style="min-width:140px;"><font face="楷体">报考专业</font></th>
      <th style="min-width:60px;"><font face="楷体">是否住校</font></th>
      <th style="min-width:100px;"><font face="楷体">所在居住地</font></th>
      <th style="min-width:70px;"><font face="楷体">联系电话</font></th>
      <th style="min-width:130px;"><font face="楷体">身份证号</font></th>
      <th style="min-width:60px;"><font face="楷体">准考证号</font></th>
      <th style="min-width:90px;"><font face="楷体">报名号</font></th>
      <th style="min-width:60px;"><font face="楷体">中考成绩</font></th>
      <th style="min-width:160px;"><font face="楷体">家庭住址</font></th>
      <th style="min-width:100px;"><font face="楷体">毕业学校</font></th>
      <th style="min-width:100px;"><font face="楷体">已交费日期</font></th>
      <th style="min-width:60px;"><font face="楷体">交费情况</font></th>
      <th style="min-width:120px;"><font face="楷体">备注</font></th>
    </tr>
    </thead>
    <tbody></tbody>
  </table>
  <div id="tableFoot" align="left">
    <font face="楷体"></font>
  </div>
</div>
</body>
</html>
